<template>
  <div class="home">
    <!-- 顶部搜索栏 -->
    <van-search show-action shape="round" background="#d81e06" placeholder="请输入搜索关键词" @click-input="handleJumpToSearch">
      <template #left>
        <van-icon name="apps-o" size="24" color="#fff" />
      </template>
      <template #action>
        <van-icon name="user-o" size="24" color="#CCC" @click="$router.push('/login')"/>
      </template>
    </van-search>

    <!-- 轮播图 -->
    <!-- <van-swipe :autoplay="3000" lazy-render hieght="180">
      <van-swipe-item v-for="image in images" :key="image.bannerid">
        <img :src="image.img" width="100%" height="100%"/>
      </van-swipe-item>
    </van-swipe> -->

    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="flushedLoading" @refresh="onRefresh">
      <!-- 使用SWiper 库 -->
      <div class="swiper-container">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-for="image in images" :key="image.bannerid">
            <img :src="image.img" width="100%" height="100%" />
          </div> 

        </div>
        <!-- 如果需要分页器 -->
        <div class="swiper-pagination"></div>
      </div>

      <!-- 宫格渲染 -->
      <van-grid :column-num="5">
        <van-grid-item v-for="grid in grids" :key="grid.text" :icon="grid.icon" :text="grid.text" />



        <!-- <van-grid-item icon="/imges/1.png" text="文字" />  -->
        <!-- <van-grid-item icon="photo-o" text="文字" />
  <van-grid-item icon="photo-o" text="文字" />
  <van-grid-item icon="photo-o" text="文字" />
  <van-grid-item icon="photo-o" text="文字" />
  <van-grid-item icon="photo-o" text="文字" /> -->

      </van-grid>


      <!-- 秒杀商品 -->
      <div class="skill">
        <span class="title">商品秒杀</span>
        <van-count-down :time="time">
          <template #default="timeData">
            <span class="block">{{ timeData.hours }}</span>
            <span class="colon">:</span>
            <span class="block">{{ timeData.minutes }}</span>
            <span class="colon">:</span>
            <span class="block">{{ timeData.seconds }}</span>
          </template>
        </van-count-down>
      </div>
      <van-grid :column-num="4" :border="false" icon-size="100">
        <van-grid-item v-for="skill in skills" :key="skill.proid" :icon="skill.img1" :text="skill.originprice" @click="jumpToDetail(skill.proid)" />

      </van-grid>
      <!-- 推荐商品 -->
      <van-divider>推荐商品</van-divider>

      <!-- 列表加载  触底可加载更多 -->
      <van-list :immediate-check="false" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
        @load="handleLoadMore">
        <div class="recommend-list">
          <div class="recommend-list-item" v-for=" prod in recommends" key="prod.proid" @click="jumpToDetail(prod.proid)">
            <img :src="prod.img1" alt="">
            <div class="title van-ellipsis">{{ prod.proname }}</div>
            <div class="price">
              <span>{{ prod.originprice * prod.discount / 10 }}</span>
              <span>原价：{{ prod.originprice }}</span>
            </div>
            <div class="sales">销量：{{ prod.sales }}</div>
          </div>

        </div>
      </van-list>

      <!-- 回到顶部 -->
      <van-back-top bottom="20vh" :offset="1000" />
    </van-pull-refresh>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { showToast } from 'vant';
import { useRouter } from 'vue-router';
import { getBanners, getSecKillList, getRecommendList } from "@/api/home"

//@ts-ignore
import Swiper from "swiper/swiper-bundle"
import "swiper/swiper-bundle.css"


// 可以将图像资源作为模块引入
// import png1 from "@/assets/2.png"

const router = useRouter()

// 跳转搜索页面
const handleJumpToSearch = () => {
  router.push("./search")
}

//轮播图
const images = ref<Banner[]>([])
const fetchData = async () => {
  try {
    const result = await getBanners()
    console.log("轮播图数据:", result)
    images.value = result
    // 下一次DOM更新后，渲染轮播图
    nextTick(() => {
      new Swiper('.swiper-container', {
        autoplay: true, //自动轮播
        loop: true, // 循环模式选项

        effect: "fade",
        // 如果需要分页器
        pagination: {
          el: '.swiper-pagination',
        },

      })

    })
  } catch (error) {
    console.error("异常:", error)
  }
}


// 宫格数据
//根据文件名称，引入资源
function getImagUrl(name: number | string) {
  return new URL(`../../assets/${name}.png`, import.meta.url).href
}
const grids = ref([
  { icon: getImagUrl(1), text: "点点购物" },
  { icon: getImagUrl(2), text: "点点数码" },
  { icon: getImagUrl(3), text: "服饰美妆" },
  { icon: getImagUrl(4), text: "充值购物" },
  { icon: getImagUrl(5), text: "PLUS 会员" },

])

//秒杀 ，倒计时
const time = ref(30 * 60 * 60 * 1000);
const skills = ref<Product[]>([])
const fetchSKill = async () => {
  try {
    const result = await getSecKillList()
    console.log("秒杀商品", result)
    skills.value = result
  } catch (error) {
    console.log("异常:", error)
  }
}
fetchSKill()

// 推荐商品 
const recommends = ref<Product[]>([])//所有推荐商品
const loading = ref<boolean>(false)//是否正在加载更多数据中
const finished = ref<boolean>(false)//是否全部数据加载完毕
const page = ref<number>(1)

const fetchRecommendlist = async () => {
  try {
    const result = await getRecommendList()
    console.log("推荐商品：", result)
    recommends.value = result

  } catch (error) {
    console.error("异常：", error)
  }
}
const handleLoadMore = async () => {
  console.log("加载更多数据....")
  //加载更多的数据，则页码增加1
  page.value += 1
  //查询更多的推荐上平数据
  try {
    const result = await getRecommendList({ page: page.value, pageSize: 10 })
    console.log("推荐商品：", result)
    //将查询出的商品数据与已有的推荐商品数据合并
    // recommends.value = recommends.value.concat(result)
    recommends.value = [
      ...recommends.value,
      ...result,
    ]

    //将loading 设置为 false 表示当前次加载完毕
    loading.value = false
    //判断是否全部数据查询完毕
    //可通过当前次查询结果数组的长度来判断
    //查询结果数组长度不为 10 时，则说明 全部数据调查完毕
    finished.value = result.length !== 12


  } catch (error) {
    console.error("异常：", error)
  }
}

fetchData()

fetchRecommendlist()

//下拉刷新
const count = ref(0);
const flushedLoading = ref(false);
const onRefresh = () => {
  setTimeout(() => {
    showToast('刷新成功');
    flushedLoading.value = false;
    count.value++;
  }, 1000);
};

// 点击商品项，向详情页面跳转
const jumpToDetail = (proid:string) =>{
  router.push({
    path:"/detail",
    query:{//传递？查询字符串参数
      proid,
    },
    // params:{//传递参数路径，不能和 path 共存，通常和name属性一起使用（命名路由）
    // }
  })
}
</script> 

<style lang="less" scoped>
.van-icon-apps-o {
  margin-right: 6px;
}

.swiper-container {
  width: 100%;
  height: 180px;
}

.skill {
  display: flex;
  align-items: center;
  padding: 6px;
}

.colon {
  display: inline-block;
  margin: 0 4px;
  color: #1989fa;
}

.block {
  display: inline-block;
  width: 22px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background-color: #1989fa;
}

.recommend-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  &-item {
    width: 43%;
    display: flex;
    flex-direction: column;
    box-shadow: 1px 1px 5px #ccc;
    margin: 6px;
    padding: 6px;
    text-align: center;

    img {
      width: 160px;
      height: 160px;
    }
  }
}
</style>





<!-- 看下列代码，将会输出什么 -->
